package cn.zl.netty.work;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @Description:聊天服务器
 * @Author: zllwsy
 * @Date: 2020/10/29 9:37
 */
public class MychatServer {
    public static void main(String[] args) {
        //1.创建一个线程组，用来接收客户端连接
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //2.创建一个线程组，处理网络操作
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        //3.创建服务端启动助手来配置参数
        ServerBootstrap serverBootstrap = new ServerBootstrap()
                 //4.设置两个线程组
                .group(bossGroup, workerGroup)
                 //5.使用NioServerSocketChannel作为服务器端通道的实现
                .channel(NioServerSocketChannel.class)
                 //6.设置线程队列中等待连接的个数
                .option(ChannelOption.SO_BACKLOG,128)
                 //7.保持活动连接状态
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                 //8.创建一个通道初始化对象 //步骤9在MyChatServerInitializer中
                .childHandler(new MyChatServerInitializer());
        try {
            System.out.println("Server is ready ...");
            //10.绑定端口，bind方法是异步的,sync方法是同步阻塞的
            ChannelFuture future = serverBootstrap.bind(52002).sync();
            System.out.println("Server is starting ...");
            //11.关闭通道，关闭线程组
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            System.out.println("Server is end ...");
        }
    }
}
